/* $RCSFile: OrderFail.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/Secure2/OrderFail.aspx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:12  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Web.Configuration;

using AddonNice.Security;
using AddonNice.Diagnostics;
using AddonNice.Configuration;
using AddonNice.UI;
using AddonNice.Authentication;
using AddonNice.Helpers;

using AddonNice.ECommerce;

using Trace2 = System.Diagnostics.Trace;

namespace AddonNice.ECommerce
{
	/// <summary>
	/// Summary description for OrderFail.
	/// </summary>
	public partial class OrderFail : AddonNice.UI.StdAuxPage
	{
		protected string orderId = "no number";
        private AddonNiceUser _currentUser = null;

        /// <summary>
        /// When in Form authentication, uses AddonNiceMembership to initialize the user
        /// When in AD mode, uses default account set in module settings/ or page settings /or site settings
        /// </summary>
        private AddonNiceUser currentUser
        {
            get
            {
                if ( TraceProducts.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]OrderFail currentUser GET BEG.",TraceProducts.Sw.Info);
                if (_currentUser == null)
                    _currentUser                =   AddonNiceUser.GetCurrent();
                if ( (_currentUser == null) || ( portalSettings.AuthMode != AuthenticationMode.Forms ) )
                {
                    try
                    {
                            string valGuid      =   moduleSettingsDic[EComStStr.DefaultAccount4Orders].Value.Trim();
                            Guid accountId      =   Guid.Empty;
                            if ( !string.IsNullOrEmpty(valGuid) ) 
                                accountId       =   new Guid(valGuid);
                            if (accountId == Guid.Empty)
                            {
                                valGuid         =   Settings[EComStStr.PageSettingsDefaultAccount4Orders].Value.Trim();
                                if (!string.IsNullOrEmpty(valGuid))
                                    accountId   =   new Guid(valGuid);
                            }
                            if ( accountId == Guid.Empty )
                            {
                                valGuid         =   portalSettings.CustomSettings[EComStStr.SiteSettingsDefaultAccount4Orders].Value.Trim();
                                if (!string.IsNullOrEmpty(valGuid))
                                    accountId   =   new Guid(valGuid);
                            }
                            string sellingFrom  =   portalSettings.CustomSettings[EComStStr.SiteSettingsSellingCountry].Value.Trim();
                            _currentUser        =   new EcommerceUser(accountId,sellingFrom);
                    }
                    catch (Exception ex)
                    {
                        if ( TraceProducts.Sw.TraceError )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderFail currentUser Get ex: {0}", ex),TraceProducts.Sw.Info);
                        throw;
                    }
                }
                if (_currentUser == null)
                {
                    const string msg            =   "[E]OrderFail currentUser is NULL";
                    if ( TraceProducts.Sw.TraceError )
                        Trace2.WriteLine(msg,TraceProducts.Sw.Info);
                    throw new Exception(msg);
                }
                if ( TraceProducts.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderFail currentUser Get Key: [{0}],userName: [{1}]",
                         _currentUser.ProviderUserKey, _currentUser.UserName),TraceProducts.Sw.Info);
                return _currentUser;

            }
        }
        
        /// <summary>
        /// In Form authentication, this is the Crm customer
        /// In AD the default account set in site settings
        /// </summary>
        private CrmCustomerId CrmUserID
        {
            get
            {
                return currentUser.CrmCustomer;
            }
        }

        /// <summary>
        /// In Form authentication, this is the Membership Guid Key
        /// In AD the default account set in site settings
        /// </summary>
        private Guid UserID
        {
            get
            {
                return currentUser.ProviderUserKey;
            }
        }

		protected void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				orderId = Request.Params["orderid"];
				// load the order
				Order2 order    =   new Order2();
				order.Load(new Guid(orderId));

				// check that the user can see this order
				if ( UserID != order.CustomerID ) 
				{
                    if ( TraceProducts.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderFail Page_Load bad user detected UserID: {0}, order.CustomerID: {1}",
                             UserID != order.CustomerID),TraceProducts.Sw.Info);
					Security.PortalSecurity.AccessDeniedEdit();
				}

				if ( !IsPostBack ) 
				{
					receiptPlaceHolder.Controls.Add(new LiteralControl(order.OrderHtml));
				}
			}
			catch
			{
			}
		}

		/// <summary>
		/// Redirect user back to the Portal Home Page or page id saved in session
		/// </summary>
		protected void ContinueBtn_Click(object sender, System.EventArgs e)
		{
			PortalSecurity.PortalHome(true,this);
		}

        #region Std Overrides

        ImageButton ContinueBtn =   null;

        protected override void OnPreInit(EventArgs e)
        {
            MasterPage m                =   Master; // to instanciate all controls Cf bug asp.ent
            string strcult              =   LocalizeHelper.GetCurrentNeutralCultureName();
            ContinueBtn                 =   new ImageButton();
            ContinueBtn.ID              =   "BtnContinue";
            ContinueBtn.SkinID          =   "next_" + strcult;
            PlaceHolderButtons.Controls.Add(ContinueBtn);

            base.OnPreInit(e);
        }


		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
            Load                +=  new EventHandler(Page_Load);
            ContinueBtn.Click   +=  new ImageClickEventHandler(ContinueBtn_Click);
		}

		#endregion

	}
}
